package com.uenpay.oem.ui.trans.transfer;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qyx.android.message.type.PacketType;
import com.socks.library.KLog;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.oem.MyApplication;
import com.uenpay.oem.R;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.data.bean.TransPayType;
import com.uenpay.oem.data.bean.WrapPayType;
import com.uenpay.oem.ui.main.home.HomeNewFragment;
import com.uenpay.oem.ui.main.my.MyFragment;
import com.uenpay.oem.ui.reserver.AddnewcardActivity;
import com.uenpay.oem.ui.verifyinput.VerifyInputActivity;
import com.uenpay.oem.ui.withdraw.WithdrawActivity;
import com.uenpay.oem.util.BankCardUtil;
import com.uenpay.oem.widget.dialog.PayTypeListDialog;
import com.uenpay.oem.widget.dialog.UenChooseDialog;
import com.uenpay.oem.widget.listener.AmountEditTextWatcher;
import com.uenpay.res.widget.dialog.LoadDialog;
import com.uenpay.service.bean.BankCardInfo;
import com.uenpay.service.bean.TransBankCardList;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.common.StringUtils;
import com.uenpay.util.imageloader.ImageLoader;
import com.uenpay.util.imageloader.ImageLoaderUtil;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author: liulou
 * Date: 2017/6/23.
 * desc:
 */

@Route(path = "/trans/transfer")
public class TransferActivity extends BaseActivity implements TransferContract.View {

    private static final String TAG = "TransferActivity";

    public static final int REQUEST_INPUT_PASSWORD = 202; //密码
    public static final int REQUEST_INPUT_CODE = 203;  //验证码
    public static final int REQUEST_INPUT_RESULT = 204;  //结果界面

    @BindView(R.id.iv_transfer_avatar)
    ImageView ivTransferAvatar;
    @BindView(R.id.tv_transfer_name)
    TextView tvTransferName;
    @BindView(R.id.et_transfer_amount)
    EditText etTransferAmount;
    @BindView(R.id.et_transfer_msg)
    EditText etTransferMsg;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.rl_choose_paytype)
    RelativeLayout rlChoosePayType;
    @BindView(R.id.iv_bankcard_icon)
    ImageView ivBankcardIcon;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_type)
    TextView tvBankType;

    private String amount;
    private String nickName;
    private String custId;

    //交易请求成功返回信息，发送验证码
    private String mWkPayNo;
    private String mTradeNo;
    private String mPayType;

    private TransBankCardList<BankCardInfo> mTransBankCardList;
    private TransferContract.Presenter mTransferPresenter;
    private List<WrapPayType> mPaytypeList = null;
    private int mSelectedPosition = -1;

    private PayTypeListDialog mPayTypeListDialog = null;

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_transfer;
    }

    @Override
    public void initView(View view) {
        setPresenter(null);
        setTitle(getString(R.string.title_transfer));
        if (getIntent() != null) {
            amount = getIntent().getStringExtra("amount");
            nickName = getIntent().getStringExtra("nickname");
            custId = getIntent().getStringExtra("custid");
            KLog.d(TAG, "[initView]  amount=" + amount + " nickname=" + nickName + " custid=" + custId);
        }
        String avaterUrl = APIConfiguration.getAvatarUrlBig(custId, PacketType.PERSONAL);
        ImageLoaderUtil.getInstance().loadImage(this, new ImageLoader.Builder().url(avaterUrl).roundRadius(6).imgView(ivTransferAvatar).build());
        tvTransferName.setText("向个人用户（" + nickName + "）转账");
        if (!TextUtils.isEmpty(amount)) {
            etTransferAmount.setText(amount);
        }
        etTransferAmount.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etTransferAmount.addTextChangedListener(new AmountEditTextWatcher(etTransferAmount));
        mTransferPresenter.getTransBankCardList();
    }

    @Override
    public void showLoading() {
        LoadDialog.show(this);
    }

    @Override
    public void dismissLoading() {
        LoadDialog.dismiss(this);
    }

    @Override
    public void setPresenter(Object presenter) {
        mTransferPresenter = new TransferPresenter(this);
    }

    @Override
    public void showToast(String msg) {
        Toasts.shortToast(this, msg);
    }

    @Override
    public void transferSuccess() {

        Intent intent = new Intent(TransferActivity.this, TransferResultActivity.class);
        intent.putExtra("amount", amount);
        intent.putExtra("name", nickName);
        intent.putExtra("msg", etTransferMsg.getText().toString().trim());
        RxBus.$().post(MyFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
        RxBus.$().post(HomeNewFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
        startActivityForResult(intent, REQUEST_INPUT_RESULT);


    }

    @Override
    public void returnTradeInfo(String wkPayNo, String tradeNo, String payType) {
        mWkPayNo = wkPayNo;
        mTradeNo = tradeNo;
        mPayType = payType;
        Intent intent = new Intent(TransferActivity.this, VerifyInputActivity.class);
        intent.putExtra("title", "请输入验证码");
        BankCardInfo cardInfo = (BankCardInfo) mPaytypeList.get(mSelectedPosition).getObject();
        intent.putExtra("subtitle", "验证码已发送至 " + cardInfo.getPhone());
        intent.putExtra("amount", amount);
        intent.putExtra("show_send_retry", true);
        intent.putExtra("show_pwd", true);
        intent.putExtra("input_length", 6);
        startActivityForResult(intent, REQUEST_INPUT_CODE);
    }

    @Override
    public void payPwdError() {
        final UenChooseDialog uenChooseDialog = new UenChooseDialog(this, TransferActivity.this);
        uenChooseDialog.setMessage("支付密码不正确，请重试");
        uenChooseDialog.setOnCancleClickListener(new UenChooseDialog.OnCancleListener() {

            @Override
            public void onCancle() {
                uenChooseDialog.dismiss();
            }
        });
        uenChooseDialog.setOnConfirmClickListener(new UenChooseDialog.OnConfirmListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent(TransferActivity.this, VerifyInputActivity.class);
                intent.putExtra("title", "请输入支付密码");
                intent.putExtra("subtitle", "向个人用户（" + nickName + "）转账");
                intent.putExtra("amount", amount);
                intent.putExtra("forget_pwd", true);
                intent.putExtra("show_pwd", false);
                intent.putExtra("input_length", 6);
                startActivityForResult(intent, REQUEST_INPUT_PASSWORD);
                uenChooseDialog.dismiss();
            }
        });
        uenChooseDialog.show();
    }


    @OnClick(R.id.btn_confirm)
    public void onBtnConfirm() {
        amount = etTransferAmount.getText().toString().trim();
        if (TextUtils.isEmpty(amount)) {
            Toasts.shortToast(this, "请输入转账金额");
            return;
        }
        if (mSelectedPosition == -1) {
            Toasts.shortToast(this, "请选择支付方式");
            return;
        }
        if (mPaytypeList.get(mSelectedPosition).getType() == TransPayType.BALANCE) {
            double balance = Double.parseDouble(MyApplication.getBalance());
            if (balance < Double.parseDouble(amount)) {
                Toasts.shortToast(this, "账户余额不足，请充值或选择其他支付方式");
                return;
            }
            Intent intent = new Intent(TransferActivity.this, VerifyInputActivity.class);
            intent.putExtra("title", "请输入支付密码");
            intent.putExtra("subtitle", "向个人用户（" + nickName + "）转账");
            intent.putExtra("amount", amount);
            intent.putExtra("forget_pwd", true);
            intent.putExtra("show_pwd", false);
            intent.putExtra("input_length", 6);
            startActivityForResult(intent, REQUEST_INPUT_PASSWORD);
            return;
        } else if (mPaytypeList.get(mSelectedPosition).getType() == TransPayType.BANKCARD) {
            BankCardInfo bankCardInfo = (BankCardInfo) mPaytypeList.get(mSelectedPosition).getObject();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("bank_id", bankCardInfo.getUserBankId());
                jsonObject.put("remark", etTransferMsg.getText().toString().trim());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mTransferPresenter.sendTransfer(custId, amount, "", getTransPayType(), jsonObject.toString());
        }


    }

    @OnClick(R.id.rl_choose_paytype)
    public void choosePayType() {
        if (mPayTypeListDialog == null) {
            mPaytypeList = getPayType();
            mPayTypeListDialog = new PayTypeListDialog(this, mPaytypeList);
            mPayTypeListDialog.setOnAddListener(new PayTypeListDialog.onAddClickListenner() {
                @Override
                public void onaddclick() {
                    //添加银行卡
                    Intent intent = new Intent(TransferActivity.this, AddnewcardActivity.class);
                    startActivity(intent);
                    mPayTypeListDialog.dismiss();
                }
            });
            mPayTypeListDialog.setOnChooseBankListener(new PayTypeListDialog.OnChooseBankListener() {
                @Override
                public void choose(int position) {
                    mSelectedPosition = position;
                    setSelectedPayType(mPaytypeList.get(position));
                }
            });

            //点击关闭
            mPayTypeListDialog.setOnCloseListener(new PayTypeListDialog.onCloseClickListener() {
                @Override
                public void oncloseClick() {
                    mPayTypeListDialog.dismiss();
                }
            });
        }
        if (mSelectedPosition != -1 && mPayTypeListDialog.getChoosePayTypeAdapter() != null) {
            mPayTypeListDialog.getChoosePayTypeAdapter().setChoosePosition(mSelectedPosition);
        }
        mPayTypeListDialog.show();
    }

    @Override
    public void setTransBankCardList(TransBankCardList<BankCardInfo> list) {
        mTransBankCardList = list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == REQUEST_INPUT_PASSWORD) {
            KLog.d(TAG, "[onActivityResult] password=" + data.getStringExtra("pwd"));
            mTransferPresenter.sendTransfer(custId, amount, data.getStringExtra("pwd"), getTransPayType(), etTransferMsg.getText().toString().trim());
        } else if (requestCode == REQUEST_INPUT_CODE) {
            KLog.d(TAG, "[onActivityResult] code=" + data.getStringExtra("pwd"));
            mTransferPresenter.checkCode(mTradeNo, mWkPayNo, data.getStringExtra("pwd"));
        } else if (requestCode == REQUEST_INPUT_RESULT) {
            setResult(RESULT_OK);
            finish();
        }
    }

    /**
     * 封装
     *
     * @return
     */
    private List<WrapPayType> getPayType() {
        List<WrapPayType> payTypes = new ArrayList<>();
        payTypes.add(new WrapPayType(TransPayType.BALANCE, null));
        if (mTransBankCardList != null && mTransBankCardList.getBankCardList().size() > 0) {
            for (BankCardInfo info : mTransBankCardList.getBankCardList()) {
                payTypes.add(new WrapPayType(TransPayType.BANKCARD, info));
            }
        }
        return payTypes;
    }

    private void setSelectedPayType(WrapPayType payType) {
        TransPayType type = payType.getType();
        if (type == TransPayType.BALANCE) {
            tvBankName.setText("余额（¥" + MyApplication.getBalance() + ")");
            tvBankType.setVisibility(View.GONE);
            ivBankcardIcon.setImageResource(R.drawable.ic_paytype_balance);
        } else if (type == TransPayType.BANKCARD) {
            BankCardInfo info = (BankCardInfo) payType.getObject();
            tvBankName.setText(info.getBankName() + "(" + BankCardUtil.getLast4NumOfBankCard(info.getCardNo()) + ")");
            ivBankcardIcon.setImageResource(BankCardUtil.getLogoByBankName(info.getBankName()));
            tvBankType.setText(BankCardUtil.getBankCardType(info.getCardType()));
            tvBankType.setVisibility(View.VISIBLE);
        } else if (type == TransPayType.ALIPAY) {
            tvBankName.setText(R.string.paytype_alipay);
            tvBankType.setVisibility(View.GONE);
            ivBankcardIcon.setImageResource(R.drawable.ic_alipay_logo);
        } else if (type == TransPayType.WEIXIN) {
            tvBankName.setText(R.string.paytype_weixin);
            tvBankType.setVisibility(View.GONE);
            ivBankcardIcon.setImageResource(R.drawable.ic_alipay_logo);
        }
    }

    /**
     * 获取向后台传送的支付类型
     */
    private String getTransPayType() {
        String type = "";
        if (mSelectedPosition == -1) {
            return type;
        }
        WrapPayType payType = mPaytypeList.get(mSelectedPosition);
        if (payType == null) return type;
        if (payType.getType() == TransPayType.BANKCARD) {
            return "99";
        } else if (payType.getType() == TransPayType.WEIXIN) {
            return "2";
        } else if (payType.getType() == TransPayType.ALIPAY) {
            return "1";
        } else if (payType.getType() == TransPayType.BALANCE) {
            return "4";
        }
        return type;
    }

}
